
//
//  TopicViewController.m
//  cookBook
//
//  Created by xalo on 16/1/22.
//  Copyright © 2016年 张广斌. All rights reserved.
//

#import "TopicViewController.h"
#import "TopicDetailListViewController.h"
#import "HTTPHelper_topic.h"
#import "Model.h"
#import "TopicViewCell.h"
#import "PickerView.h"
@interface TopicViewController ()

//当前页数
@property (nonatomic,assign) NSInteger number;

//选择视图
@property (nonatomic, strong)  PickerView *pickerView;

//菊花转
@property (nonatomic,strong) MBProgressHUD *HUD;

@end

@implementation TopicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
        
    //初始化number
    self.number = 1;
    
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    
    //加载数据
    [self setNetDataWithNumber:self.number];
    
    //下拉刷新
    [self dropdownRefresh];
    
    //上拉加载
    [self pullOnLoading];
    
    UIImage *image = [[UIImage imageNamed:@"hand"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:(UIBarButtonItemStylePlain) target:self action:@selector(packerAction)];
   
    
}

- (void)packerAction {
    
    
    //初始化
    self.pickerView = [[PickerView alloc] initWithFrame:[UIScreen mainScreen].bounds PageNumber:14 currentRow:self.number - 1];
    
    //添加到window上
    [[UIApplication sharedApplication].keyWindow addSubview:self.pickerView];
    __weak TopicViewController *weakSelf = self;
    
    //block赋值
    self.pickerView.block = ^(NSInteger page){
        
        //传递选择的页数
        weakSelf.number = page;
        
        //清空数据请求单例中数组中model
        [[HTTPHelper_topic shareHelper].topicListArray removeAllObjects];
        
        //刷新页面
        [weakSelf.tableView reloadData];
        
        //根据传递的参数请求数据
        [weakSelf setNetDataWithNumber:weakSelf.number];
        
        //判断数据请求中是否有数据
        if ([HTTPHelper_topic shareHelper].topicListArray.count != 0) {
            
            //第一行移动至顶端
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            
            [weakSelf.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionTop)];
        }
        
    };

    
}

//
//请求数据
-(void)setNetDataWithNumber:(NSInteger)number
{
    
    

    if (number < 15) {
  
        // 添加加载视图
        self.HUD.labelText = @"正在加载";
        
        self.HUD.removeFromSuperViewOnHide = YES;
        
        [self.view addSubview:self.HUD];
        [self.HUD show:YES];

    
        
        NSString *urlStr = [NSString stringWithFormat:@"http://ibaby.ipadown.com/api/food/food.topic.list.php?p=%ld&pagesize=12&order=views",number];

        __weak TopicViewController *weakSelf = self;
        
        //请求数据
        [[HTTPHelper_topic shareHelper] fetchTopicListWithUrl:urlStr block:^{
            
            [weakSelf.tableView reloadData];
            
            weakSelf.number++;
            
            // 加载视图消失
            weakSelf.HUD.removeFromSuperViewOnHide = YES;
            [weakSelf.HUD hide:YES];

        
        }];
        
    }


}
// 下拉刷新
- (void)dropdownRefresh
{
    __weak TopicViewController *weakSelf = self;
    
    // 下拉刷新数据
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        weakSelf.number = 1;
        
        
        // 把数组里面的数据置为空
        
        [[HTTPHelper_topic shareHelper].topicListArray removeAllObjects];
        
        [weakSelf setNetDataWithNumber:weakSelf.number];
        

        // 刷新数据
        [weakSelf.tableView reloadData];
        
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
        
    }];
    
}



// 上拉加载
- (void)pullOnLoading
{
    __weak TopicViewController *weakSelf = self;
    
    // 上拉加载数据
    self.tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        
       
        [weakSelf setNetDataWithNumber:weakSelf.number];
        
        [weakSelf.tableView reloadData];
        
        // 判断是否大于14,大于14结束
        if (weakSelf.number < 15) {
            
            // 结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            
        }
        else
        {
            weakSelf.HUD.labelText = @"已经到底了";
            
            [weakSelf.view addSubview:self.HUD];
            [weakSelf.HUD show:YES];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.HUD.removeFromSuperViewOnHide = YES;
                [weakSelf.HUD hide:YES];
                
            });
            // 结束
            [weakSelf.tableView.mj_footer endRefreshing];

        
        }
        
    }];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [[HTTPHelper_topic shareHelper] countOfTopicListArray];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TopicViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topicCell" forIndexPath:indexPath];
    
    //获取index行对应的model
    Model *model = [[HTTPHelper_topic shareHelper] returnModelWithIndex:indexPath.row];
    
    
    //根据index设置每个单元格
    [cell setContentViewWithModel:model];
    
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Model *model = [[HTTPHelper_topic shareHelper] returnModelWithIndex:indexPath.row];
    
    
    TopicDetailListViewController *listVC = [[UIStoryboard storyboardWithName:@"TopicSB" bundle:nil] instantiateViewControllerWithIdentifier:@"listVC"];
    listVC.ID = model.ID;
    listVC.title = model.title;
    
    [self.navigationController pushViewController:listVC animated:YES];


}






/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
